package com.kkkitsch.coolalbum.controller;

import static com.kkkitsch.coolalbum.common.MyConstant.UPLOAD_ERROR_MSG;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.kkkitsch.coolalbum.common.MyAcctAndId;
import com.kkkitsch.coolalbum.common.MyConstant;
import com.kkkitsch.coolalbum.entity.TMember;
import com.kkkitsch.coolalbum.entity.TPhoto;
import com.kkkitsch.coolalbum.entity.TPhototype;
import com.kkkitsch.coolalbum.service.TPhotoService;
import com.kkkitsch.coolalbum.service.TPhototypeService;
import com.kkkitsch.coolalbum.util.ImageClientUtil_V;
import com.kkkitsch.coolalbum.util.MyMsg;

@Controller
@RequestMapping("/photo")
public class TPhotoController {

	@Autowired
	TPhotoService photoServiceImpl;

	@Autowired
	TPhototypeService phototypeServiceImpl;

	@RequestMapping("/readyplaypic")
	public String toPlayPic() {
		return "redayplay_pic";
	}

	@RequestMapping("/showpreview")
	@ResponseBody
	public MyMsg<Map<String, Object>> playPic(HttpSession session) {
		MyMsg<List<TPhototype>> content = phototypeServiceImpl.getPhototype(MyAcctAndId.getMyId(session), session);

		List<TPhototype> phototype = content.getContent();

		Map<String, Object> contentMap = new HashMap<String, Object>();
		contentMap.put("phototype", phototype);

		Map<String, Object> photoMap = new HashMap<String, Object>();
		for (TPhototype tPhototype : phototype) {
			// 遍历photo
			TPhoto tPhoto = photoServiceImpl.playPic(tPhototype.getpMemberId(), tPhototype.getpId());
			if (tPhoto != null) {
				photoMap.put(tPhototype.getpId().toString(), tPhoto);
			}
		}
		contentMap.put("photo", photoMap);
		return MyMsg.success("ok", contentMap, null);
	}

	@GetMapping("/nowplay")
	public String nowPlay(String pTypeId, Model model) {
		model.addAttribute("ptypeid", pTypeId);
		return "play_pic";
	}

	@GetMapping("/playtypepic")
	@ResponseBody
	public MyMsg<List<TPhoto>> playTypePic(String pTypeId) {
		return photoServiceImpl.playTypePic(pTypeId);
	}

	/**
	 * 上传图片
	 */
	@RequestMapping("/upload")
	public String upload(@RequestParam("upFile") MultipartFile[] file, TPhoto photo, HttpSession session, Model model) {

		// 获取目录的真实路径
		String realPath = session.getServletContext().getRealPath("/image");

		// 使用标签
		// 默认情况下，即使没有选择文件，MultipartFile数组的长度也不为空，而是存在一个空文件，你必须遍历判断其中的文件是否为空
		findErrorImg: for (MultipartFile cur_file : file) {

			// 防止用户名重复，重新改变文件名
			String newFilename = "";
			// 如果文件不为空
			if (!cur_file.isEmpty()) {
				newFilename = UUID.randomUUID().toString().substring(0, 11).replaceAll("-", "")
						+ cur_file.getOriginalFilename();
				// 如果不是图片
				if (!cur_file.getContentType().contains("image")) {
					model.addAttribute(UPLOAD_ERROR_MSG, MyMsg.fail("上传失败，不是一个图片", photo, null));
					return "member_home";
				}
				// 如果图片超过了4M
				if (4 * 1024 * 1024 < cur_file.getSize()) {
					model.addAttribute(UPLOAD_ERROR_MSG, MyMsg.fail("上传失败，请上传小于4M的图片", photo, null));
					return "member_home";
				}
			} else {
				// 文件为空
				model.addAttribute(UPLOAD_ERROR_MSG, MyMsg.fail("请选择图片！", null, null));
				return "member_home";
			}
			try {
				// 由于使用的是免费接口，qps有限制，故意设置此休眠
				Thread.sleep(250);

				// 百度云图像审核接口验证
				String validation = ImageClientUtil_V.validation(cur_file);
				System.out.println("===>" + validation);

				// 复杂json数据 -第一层
				@SuppressWarnings("rawtypes")
				Map mapTypes = JSON.parseObject(validation);

				for (Object obj : mapTypes.keySet()) {
					if ("result".equalsIgnoreCase(obj.toString())) {
						// 复杂json数据 -第二层
						@SuppressWarnings("rawtypes")
						Map second = JSON.parseObject(mapTypes.get(obj).toString());
						for (Object obj2 : second.keySet()) {
							// System.out.println("key：" + obj2 + "===>：" +
							// second.get(obj2));
							// 复杂json数据 -第三层
							@SuppressWarnings("rawtypes")
							Map three = JSON.parseObject(second.get(obj2).toString());
							for (Object obj3 : three.keySet()) {
								// System.out.println("\tkey：" + obj3 + "===>："
								// + three.get(obj3));

								// 鉴别色情
								if ("antiporn".equalsIgnoreCase(obj2.toString())) {
									if ("conclusion".equalsIgnoreCase(obj3.toString())) {
										if ("色情".equalsIgnoreCase(three.get(obj3).toString())) {
											// System.out.println("============有内鬼，终止交易=================");
											// 跳出此循环，验证执行下一个图片
											continue findErrorImg;
										}
									}
								}

								// 鉴别暴恐
								if ("terror".equalsIgnoreCase(obj2.toString())) {
									if ("result".equalsIgnoreCase(obj3.toString())) {

										double d = Double.parseDouble(three.get(obj3).toString());
										double r = 1.0000000d;
										if ((r - d) < 0.1) {
											// System.out.println("============有内鬼，终止交易=================");
											continue findErrorImg;
										}
									}
								}
								// 复杂json数据 -第四层
							}
						}
					}
				}

				// 保存到本地
				cur_file.transferTo(new File(realPath + File.separator + newFilename));
			} catch (IOException e) {
				System.out.println("上传失败");
				continue;
			} catch (Exception e) {
				System.out.println("百度云接口验证失败");
				e.getStackTrace();
				continue;
			}
			String netUrl = "image/" + newFilename;
			// 设置图片的默认属性
			photo.setpCreatetime(new Date());
			photo.setpLikenum(0);
			photo.setpUrl(netUrl);
			photo.setpName(newFilename);
			photo.setpModitytime(new Date());
			photo.setpMemberId(((TMember) session.getAttribute(MyConstant.CUR_MEMBER)).getmId());
			// 保存
			MyMsg<TPhoto> myMsg = photoServiceImpl.uploadFile(photo);
			// System.out.println("============没有内鬼，交易完成=================");
			// 去除自增主键，直接操作photo即可，因为传递的是各个引用，photo==myMsg.getContent();
			photo.setpId(null);
			// 判断是否保存成功！
			if (myMsg.getCode() != 1) {
				model.addAttribute(UPLOAD_ERROR_MSG, myMsg.getMsg());
			}
		}
		// 防止重复提交表单
		return "redirect:/member_home.html";

	}

	/**
	 * 获取所有图片
	 */
	@RequestMapping("/getAllPhoto")
	@ResponseBody
	public MyMsg<List<TPhoto>> getAllPhoto(HttpSession session) {
		return photoServiceImpl.getAllPhoto(MyAcctAndId.getMyId(session),
				phototypeServiceImpl.getPhototype(MyAcctAndId.getMyId(session), session).getContent(), session);
	}

	/**
	 * 指定图片信息
	 */
	@RequestMapping("/getDelicatedPhoto")
	@ResponseBody
	public MyMsg<TPhoto> getDelicatedPhoto(String pId) {
		return photoServiceImpl.getDelicatedPhoto(pId);
	}

	/**
	 * 图片点赞
	 */
	@RequestMapping("/clicklike")
	@ResponseBody
	public MyMsg<TPhoto> ifClickLike(TPhoto photo, HttpSession session) {
		return photoServiceImpl.updateClickNum(photo, MyAcctAndId.getMyId(session));
	}

	/**
	 * 图片删除
	 */
	@RequestMapping("/singledelete")
	@ResponseBody
	public MyMsg<TPhoto> singleDelete(String pId) {
		return photoServiceImpl.singleDelete(pId);
	}
}
